package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.listener.easyexcel.SysClientRegisterListener;
import com.settlement.system.model.entity.SysClientRegister;
import com.settlement.system.model.form.SysClientRegisterForm;
import com.settlement.system.model.query.SysClientRegisterQuery;
import com.settlement.system.model.vo.SysClientRegisterImportVo;
import com.settlement.system.service.SysClientRegisterService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 客服登记表 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2024-03-29
 */
@RestController
@RequestMapping("/api/v1/clientRegister")
@RequiredArgsConstructor
public class SysClientRegisterController {

    private final SysClientRegisterService sysClientRegisterService;

    @GetMapping("/page")
    public PageResult<SysClientRegister> getPage(@ParameterObject SysClientRegisterQuery queryParams) {
        Page<SysClientRegister> result = sysClientRegisterService.getPage(queryParams);
        return PageResult.success(result);
    }


    @Operation(summary = "保存客服登记表", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreventDuplicateSubmit
    @PreAuthorize("@ss.hasPerm('sys:clientRegister:save')")
    public Result<?> saveSysClientRegister(@RequestBody @Valid SysClientRegisterForm sysClientRegisterForm) {
        boolean result = sysClientRegisterService.saveSysClientRegister(sysClientRegisterForm);
        return Result.judge(result);
    }

    @Operation(summary = "获取客服登记表信息", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{id}/form")
    public Result<SysClientRegisterForm> getSysClientRegisterFormData(@Parameter(description = "主键ID") @PathVariable Long id) {
        SysClientRegisterForm sysClientRegister = sysClientRegisterService.getSysClientRegisterFormData(id);
        return Result.success(sysClientRegister);
    }

    @Operation(summary = "删除客服登记表", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:clientRegister:delete')")
    public Result<?> deleteSysClientRegister(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = sysClientRegisterService.deleteSysClientRegister(ids);
        return Result.judge(result);
    }

    @Operation(summary = "客服登记表导入", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/sysClientRegisterImport")
    @PreAuthorize("@ss.hasPerm('sys:clientRegister:import')")
    @PreventDuplicateSubmit
    public Result<?> sysClientRegisterImport(@RequestParam("file") MultipartFile file) throws Exception {
        SysClientRegisterListener listener = new SysClientRegisterListener();
        EasyExcelFactory.read(file.getInputStream(), SysClientRegisterImportVo.class, listener).sheet(0).doRead();
        List<SysClientRegisterImportVo> list = listener.getVos();
        if (list == null || list.size() == 0) {
            return Result.success();
        }
        list.removeIf(SysClientRegisterImportVo::isEmpty);
        // 检查是否出现合并单元格
        if (list.stream().anyMatch(SysClientRegisterImportVo::isMerge)) {
            return Result.failed("存在合并单元格，导入失败");
        }
        sysClientRegisterService.importData(list);
        return Result.success();
    }

    @Operation(summary = "导出客服登记表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    @PreAuthorize("@ss.hasPerm('sys:clientRegister:export')")
    @PreventDuplicateSubmit
    public void export(@RequestParam("ids") String ids, HttpServletResponse response) throws IOException {
        String fileName = "客服登记表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        List<SysClientRegisterImportVo> sysClientRegisterList = sysClientRegisterService.findByIds(ids);
        EasyExcel.write(response.getOutputStream(), SysClientRegisterImportVo.class).sheet("客服登记表").doWrite(sysClientRegisterList);
    }

    @Operation(summary = "根据订单号查询", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/getByOrderNo/{orderNo}")
    public Result<?> getByOrderNo(@Parameter(description = "订单号") @PathVariable String orderNo) {
        List<SysClientRegister> list = sysClientRegisterService.getByOrderNo(orderNo);
        return Result.success(list);
    }
}

